package com.tjf.record;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaRecorder;
import android.os.Environment;
import android.util.Log;

import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Plug {

    static private AudioRecord audioRecord;

    static private boolean isRecording = false;

    static private MyCallBack myCallBack;


    private static final SimpleDateFormat sdf = new SimpleDateFormat("yyy-MM-dd HH:mm:ss.SSS");


    private static ExecutorService executorService = Executors.newFixedThreadPool(5);


    public static void startRecording(Context context, MyCallBack callBack) {

        executorService = Executors.newFixedThreadPool(5);
        executorService.submit(() -> {
            myCallBack = callBack;
            int bufferSize = AudioRecord.getMinBufferSize(
                    16000,
                    AudioFormat.CHANNEL_IN_MONO,
                    AudioFormat.ENCODING_PCM_16BIT);
            if (ActivityCompat.checkSelfPermission(context, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
                Log.d("WebSocketMager", "未获取权限");
                return;
            }

            audioRecord = new AudioRecord(MediaRecorder.AudioSource.VOICE_COMMUNICATION,
                    16000,
                    AudioFormat.CHANNEL_IN_MONO,
                    AudioFormat.ENCODING_PCM_16BIT,
                    bufferSize);
            audioRecord.startRecording();
            if (myCallBack != null) {
                myCallBack.onStart(bufferSize);
            }
            isRecording = true;
            while (isRecording) {
                short[] shortBuffer = new short[bufferSize];
                int read = audioRecord.read(shortBuffer, 0, bufferSize);
                if (read > 0) {
                    // 处理录音数据（buffer）这里可以做进一步处理
//                    Log.d("AudioRecord", "Read " + read + " bytes");
//                    long maxDecibels = RecordDecibelUtils.getMaxDecibels(com.tjf.record.ByteUtils.toBytes(shortBuffer));
//                    Log.e("maxDecibels", "maxDecibels=="+maxDecibels);
                    if (myCallBack != null) {
                        myCallBack.onSuccess(shortBuffer, read);
                    }
                    try {
                        Thread.sleep(40);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
            if (myCallBack != null) {
                myCallBack.onComplete();
            }
        });
    }

    public static String getDefaultPath(Context context) {
        return context.getExternalFilesDir
                (Environment.DIRECTORY_MUSIC).getAbsolutePath() + "/" + "yjh_audio_cache.pcm";
    }

    public static void startRecordingPcm(Context context, MyCallBack callBack) {

        executorService = Executors.newFixedThreadPool(5);

        executorService.submit(() -> {

            myCallBack = callBack;
            int bufferSize = AudioRecord.getMinBufferSize(
                    16000,
                    AudioFormat.CHANNEL_IN_MONO,
                    AudioFormat.ENCODING_PCM_16BIT);
            if (ActivityCompat.checkSelfPermission(context, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
                Log.d("WebSocketMager", "未获取权限");
                return;
            }
            audioRecord = new AudioRecord(MediaRecorder.AudioSource.VOICE_COMMUNICATION,
                    16000,
                    AudioFormat.CHANNEL_IN_MONO,
                    AudioFormat.ENCODING_PCM_16BIT,
                    bufferSize);
            audioRecord.startRecording();
            if (myCallBack != null) {
                myCallBack.onStart(bufferSize);
            }
            isRecording = true;
            String audioCacheFilePath = getDefaultPath(context);
            File file = new File(audioCacheFilePath);
            if (file.exists()) {
                file.delete();
            }
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }

            FileOutputStream fos = null;
            try {
                fos = new FileOutputStream(file);
            } catch (Exception e) {
                e.printStackTrace();
                Log.e("录音plag", "临时缓存文件未找到");
            }
            if (fos == null) {
                return;
            }
            while (isRecording) {
                byte[] shortBuffer = new byte[bufferSize];
                int read = audioRecord.read(shortBuffer, 0, bufferSize);
                if (read > 0) {
                    try {
                        fos.write(shortBuffer, 0, read);
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
            if (myCallBack != null) {
                myCallBack.onComplete();
            }
        });
    }

    /**
     * 暂停录音
     */
    public static void endRecording() {
        if (audioRecord != null) {
            isRecording = false;
            audioRecord.stop();
            audioRecord.release();
            audioRecord = null;
            if (executorService != null) {
                executorService.shutdown();
            }
        }
    }

    //判断权限
    public static String checkAudioPermissions(Context context) {
        List<String> permissionList = new ArrayList<>();
        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
            permissionList.add(Manifest.permission.RECORD_AUDIO);
        }

        if (ContextCompat.checkSelfPermission(context, Manifest.permission.READ_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            permissionList.add(Manifest.permission.READ_EXTERNAL_STORAGE);
        }
        if (ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            permissionList.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
        }

        if (!permissionList.isEmpty()) {
            String[] permissions = permissionList.toArray(new String[permissionList.size()]);
            ActivityCompat.requestPermissions((Activity) context, permissions, 1);
            return "0";
        } else {
            return "1";
        }

    }

    public static String getCurrentTimeStr() {
        return sdf.format(new Date());
    }
}
